#include "unp.h"
#include "util.h"
#include "error.h"

#define OPEN_MAX 1024
#define INFTIM -1
int main(int argc, char *argv[])
{
    int i, maxi, listenfd, connfd, sockfd;
    int nready;
    ssize_t n;
    char buf[MAXLINE];
    socklen_t clilen;
    struct pollfd client[OPEN_MAX];
    struct sockaddr_in cliaddr, servaddr;
    char ip[32];

    listenfd = Socket(AF_INET, SOCK_STREAM, 0);

    bzero(&servaddr, sizeof(servaddr));
    servaddr.sin_family = AF_INET;
    servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
    servaddr.sin_port = htons(SERV_PORT);

    Bind(listenfd, (SA *)&servaddr, sizeof(servaddr));

    Listen(listenfd, LISTENQ);

    client[0].fd = listenfd;
    client[0].events = POLLRDNORM;
    for (i = 1; i < OPEN_MAX; i++)
        client[i].fd = -1;
    maxi = 0;

    for (;;)
    {
        nready = poll(client, maxi + 1, INFTIM);
        if (client[0].revents & POLLRDNORM)
        {
            clilen = sizeof(cliaddr);
            connfd = Accept(listenfd, (SA *)&cliaddr, &clilen);

            for (i = 1; i < OPEN_MAX; i++)
            {
                if (client[i].fd < 0)
                {
                    client[i].fd = connfd;
                    break;
                }
            }

            if (i == OPEN_MAX)
            {
                err_quit("too many clients");
            }

            client[i].events = POLLRDNORM;
            if (i > maxi)
            {
                maxi = 1;
            }
            
            Inet_ntop(AF_INET, &cliaddr.sin_addr, ip, 16); 
            printf("socket %d connected: %s:%d\n", connfd, ip, ntohs(cliaddr.sin_port));
            if (--nready <= 0)
                continue;
        }
        for (i = 1; i <= maxi; i++)
        {
            if ((sockfd = client[i].fd) < 0)
                continue;
            if (client[i].revents & (POLLRDNORM | POLLERR))
            {
                bzero(buf, MAXLINE);
                if ((n = read(sockfd, buf, MAXLINE)) < 0)
                {
                    if (errno == ECONNRESET)
                    {
                        // after receive RST, connection reset by client
                        Close(sockfd);
                        printf("close socket: %d\n", sockfd);
                        client[i].fd = -1;
                    }
                    else
                    {
                        err_sys("read error");
                    }
                }
                else if(n == 0)
                {
                    // received FIN
                    Close(sockfd);
                    printf("close socket: %d\n", sockfd);
                    client[i].fd = -1;
                }
                else
                {
                    printf("write to sock: %s", buf);
                    Writen(sockfd, buf, n);
                }

                if (--nready <= 0)
                    break;
            }
        }

    }
}
